package com.ibeetl.admin.core.gen;

import com.ibeetl.admin.core.gen.model.Attribute;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;

import com.ibeetl.admin.core.gen.model.Entity;

import java.util.ArrayList;
import java.util.List;

public class HtmlGen  implements AutoGen{

	@Override
	public void make(Target target, Entity entity) {
		
		HtmlIndexGen indexGen = new HtmlIndexGen();
		indexGen.make(target, entity);
		
//		HtmlEditGen editGen = new HtmlEditGen();
//		editGen.make(target, entity);
		
		HtmlAddGen addGen = new HtmlAddGen();
		addGen.make(target, entity);
	}
	
	@Override
	public String getName() {
		return "";
	}
	
}


class HtmlIndexGen  implements AutoGen{
	
	@Override
	public void make(Target target, Entity entity) {
		GroupTemplate gt = target.getGroupTemplate();
		Template template = gt.getTemplate("/html/index.html");
		List<Attribute> list = new ArrayList<Attribute>();
		for(Attribute attr:entity.getList()) {
			if(attr.isShowInQuery()) {
				list.add(attr);
			}
		}

		if(list.isEmpty()) {
			list.add(entity.getIdAttribute());
		}
		template.binding("entity", entity);
		template.binding("target", target);
		template.binding("attrs", list);
		String content = template.render();
		target.flush(this, content);
	}

	@Override
	public String getName() {
		return "index.html";
	}
	
}

class HtmlEditGen  implements AutoGen{
	
	@Override
	public void make(Target target, Entity entity) {
		GroupTemplate gt = target.getGroupTemplate();
		Template template = gt.getTemplate("/html/edit.html");
		template.binding("entity", entity);
		template.binding("target", target);
		String content = template.render();
		target.flush(this, content);
	}
	@Override
	public String getName() {
		return "edit.html";
	}
	
}

class HtmlAddGen  implements AutoGen{
	
	@Override
	public void make(Target target, Entity entity) {
		GroupTemplate gt = target.getGroupTemplate();
		Template template = gt.getTemplate("/html/add.html");
		template.binding("entity", entity);
		template.binding("target", target);
		int hasFile = 0;
		for(Attribute attr:entity.getList()) {
			if (attr.isId()) {
				template.binding("idcol",attr);
			}
			switch(attr.getElementType()) {
				case 7:
					template.binding("hasImage","1");
					hasFile +=1;
					break;
				case 8:
				case 9:
				case 10:
					hasFile = 2;
					break;
			}
		}
		if (hasFile>0) {
			template.binding("hasFile",hasFile);
		}
		String content = template.render();
		target.flush(this, content);
	}
	@Override
	public String getName() {
		return "add.html";
	}
	
}




